package com.huluobo.kotlinim1907a.wiget

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.widget.RelativeLayout
import com.huluobo.kotlinim1907a.R
import com.huluobo.kotlinim1907a.adapter.EMCallbackAdapter
import com.huluobo.kotlinim1907a.data.AddFriendItem
import com.hyphenate.chat.EMClient
import kotlinx.android.synthetic.main.view_add_friend_item.view.*
import org.jetbrains.anko.runOnUiThread
import org.jetbrains.anko.toast
import kotlin.math.log

/**
 * Created by lc on 2022/1/18.
 */
class AddFriendListItemView(context: Context?, attr: AttributeSet? = null) :
    RelativeLayout(context, attr) {
    fun bindView(addFriendItem: AddFriendItem) {
        if (addFriendItem.isAdded) {
            add.isEnabled = false
            add.text = context.getString(R.string.already_added)
        } else {
            add.isEnabled = true
            add.text = context.getString(R.string.add)
        }
        userName.text = addFriendItem.userName
        timestamp.text = addFriendItem.timestamp

        add.setOnClickListener {
            addFriend(addFriendItem.userName)
        }
    }

    private fun addFriend(userName: String) {
        EMClient.getInstance().contactManager()
            .aysncAddContact(userName, null, object : EMCallbackAdapter() {
                override fun onSuccess() {
                    context.runOnUiThread { toast(R.string.send_add_friend_success) }
                }

                override fun onError(code: Int, error: String?) {
                    context.runOnUiThread { toast(R.string.send_add_friend_failed) }
                    Log.i("TagA", "addFriend:$code,error:$error")
                }
            })
    }

    init {
        View.inflate(context, R.layout.view_add_friend_item, this)
    }
}